/**
 * WidgetEventLocationInput module
 */

import React,{Component} from "react";
import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import editorActions from '../../../actions/Editor/editor';
import storage from "../../../utils/storage";

class WidgetEventLocationInput extends Component{
    constructor(props) {
        super(props);
        this.state = {             
            province: "",
            city: "",
            target: ""
        };
    }
    componentWillMount(){
        this.iframe = this.getIframe();
        this.iframe.on('load', function (){
            this.gmapPicker = this.iframe[0].contentWindow.gmapPicker;
            this.geocode = this.iframe[0].contentWindow.geocode;
            this.gMapDistrictSearch = this.iframe[0].contentWindow.gMapDistrictSearch;
            this.dynamicCity = this.iframe[0].contentWindow.dynamicCity;
            this.locate_CallBack = this.iframe[0].contentWindow.locate_CallBack;
            this.gmap = this.iframe[0].contentWindow.gmap;
            this.iframe[0].contentWindow.locateCallback = (res) => this.locateCallback(res);
            this.iframe[0].contentWindow.geoCallback = () => this.geocoder_CallBack();
            this.initGeocode();
            this.gMapDistrictSearch('country', '中国', this.initProvince);
            this.geocode({
                address: "" + this.address.province + this.address.city + this.address.target
            });
            // 创建省市下拉列表
            this.iframe[0].contentWindow.dynamicSelect(this.refs.province, this.refs.city, this);
        }.bind(this));

        var data = this.props.widget.action;
        data = $.extend({
            province: "",
            city: "",
            target: ""
        }, data);

        this.address = data;
        this.setState(data);
    }
    componentDidMount(){
        this.initElements();
        this.iframe.appendTo(this.elements.gmappicker);
    }
    initProvince(){

    }
    // 右键定位
    locateCallback(details){
        let param = {
            province: details.province,
            city: details.city,
            target: details.target,
            lng: details.lng,
            lat: details.lat,
        };
        this.address = param;
        const {widget,updateWidget,setState} = this.props;
        let data = widget;
        
        data.action = $.extend({}, data.action, param);
        setState({selectedWidget: data});
        updateWidget(data);

        let me = this;
        this.dynamicCity(details.province, me.refs.city, function (){
            me.setState(param);
        });
    }
    geocoder_CallBack(details){
        if (details){
            var data = details.geocodes[0];
            if (data){
                this.locate_CallBack(data.location);
            }
        }
    }
    initElements(){
        this.elements = {
            gmappicker: $(this.refs.gmappicker)
        };
    }
    initGeocode(){
        var widget = this.props.widget;
        if (widget.action.lat && widget.action.lng){
            this.geocodeByLatLng(function (lat, lng){
                widget.action.lat = lat;
                widget.action.lng = lng;
            }.bind(this));
        }
    }
    geocodeByLatLng(callback){
        var widget = this.props.widget;
        this.geocode({
            address: widget.action.target,
            lat: widget.action.lat,
            lng: widget.action.lng,
            geocode_back: callback
        });
    }
    getIframe(){
        return $('<iframe>').attr({
            src: storage.data.CONST.urls.gmap,
            width: '240',
            height: '150',
            frameborder: 0,
            allowtransparency: 1
        });
    }
    handleOnChangeLocation(e){
        var element = $(e.target || e.srcElement),
            isSelect = element.is("select"),
            type = element.attr("name"),
            value = element.val();

        if (!isSelect){
            // 过滤特殊符号
            value = value.replace(/[!@#$%^&*()-+{}\[\];:'"！，。<>?,./]+/gi, "");
        }

        this.address[type] = value;

        var param = {};
        param[type] = value;

        this.setState(param);
    }
    handleOnLocateAddress(){
        let province = this.address.province,
            city = this.address.city,
            address = this.address.target,
            lng = this.address.lng,
            lat = this.address.lat;

        this.geocode({
            address: "" + province + city + address
        });

        const {widget,updateWidget,setState} = this.props;
        let data = widget;
        data.action = $.extend({}, widget.action, this.address);
        setState({selectedWidget: data});
        updateWidget(widget);
    }
    render(){
        const {widget} = this.props;
        const {action} = widget;
        const {lat,lng} = action;
        return (
            <div className="form-group">
                <div className="choose">
                    <select onChange={(e) => this.handleOnChangeLocation(e)} ref="province" name="province" value={this.state.province} className='form-control'></select>
                    <select onChange={(e) => this.handleOnChangeLocation(e)} ref="city" name="city" className="form-control city" value={this.state.city}>
                        <option value="">{$._("Please choose")}</option>
                    </select>
                </div>
                <div className="rowli">
                    <input id="id_target" onChange={(e) => this.handleOnChangeLocation(e)} ref="target" name="target" className="target form-control" value={this.state.target} type="text" autoFocus="" placeholder={$._('Input navigation position')} />
                    <input type="text" className="hide" defaultValue={lat} name="lat" />
                    <input type="text" className="hide" defaultValue={lng} name="lng" />
                    <div onClick={() => this.handleOnLocateAddress()} type="submit" className="geocoding-btn" data-gmap>
                        <span>{$._('Location')}</span>
                    </div>
                    <div ref="gmappicker" className="gmap-gmappicker">
                    </div>
                </div>
            </div>
        )
    }
 }

 const mapStateToProps = ({ editor, widgets}) => {
  const pageId = editor.selectedPageId;
  return {
      widget: editor.selectedWidget,
      widgets: widgets.filter(w => w.page_id === pageId),
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({...widgetsActions,...editorActions}, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(WidgetEventLocationInput);
